//导入数据库模块
const db = require("../sql/index");
//加密插件
const bcrypt = require("bcryptjs");
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
// 导入配置文件
const config = require('../config')
// 后端开发经常会有使用http请求
const request = require('request')
// 文章的处理函数模块
const path = require('path');
// 又拍云
const upyuns = require('upyun');
const fs = require('fs');
const FormData = require('form-data');
const { log } = require("console");
// const bucket = new upyuns.Bucket('sportqwe', '030306', 'MB3pbgMD5xoTYfV7hQFNMalvoNxNgdYb')
const bucket = new upyuns.Bucket('ydsports', 'sport', '3aTW7QCtkkA9z1Jcppqk0qASoRw8sQDZ')

const upyun = new upyuns.Client(bucket);
// const domain = 'http://sportqwe.test.upcdn.net/'
const domain = 'http://ydsports.test.upcdn.net/'

// 查询签到数据
exports.sign = async (req, res) => {
    const open_id = await get_openid(req)
    console.log(open_id);
    const sql = `select * from user_sign where open_id='${open_id}'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取积分数据成功！',
            data: results,
        })
    })
}
// 查询签到数据
exports.sign_record = async (req, res) => {
    const open_id = await get_openid(req)
    console.log(open_id);
    const sql = `select * from sign_record where open_id='${open_id}'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取积分数据成功！',
            data: results,
        })
    })
}
// 签到
exports.addsign = async (req, res) => {
    const { flag, openid } = await issign(req)
    if (!flag) {
        console.log('未签到', openid, !flag);
        const sql = `select * from user_sign where open_id='${openid}'`
        db.query(sql, (err, results) => {
            // console.log('签到数据', results, openid);
            // console.log(results[0].is_sign);
            if (err) return res.cc(err)
            if (results.length == 1) {
                if (results[0].is_sign == 0 || results[0].is_sign == null) {
                    const sql = `select value from sign_config`
                    db.query(sql, (err, results2) => {
                        let a = []
                        results2.map(res => {
                            a.push(JSON.parse(res.value))
                        })
                        // console.log((Number(results[0].days) + 1));
                        // console.log(Number(a[(Number(results[0].days) + 1)].sign_num));
                        // console.log(results[0].integral + a[(Number(results[0].days) + 1)].sign_num);
                        const sql2 = `update user_sign set ? where open_id='${openid}'`
                        db.query(sql2, {
                            open_id: openid,
                            integral: Number(results[0].integral) + Number(a[(Number(results[0].days) + 1)].sign_num),
                            sign_time: new Date(),
                            days: Number(results[0].days) + 1,
                            is_sign: 1
                        }, (err, results) => {
                            if (err) return res.cc(err)
                            if (results.affectedRows == 1) {
                                res.send({
                                    status: 200,
                                    message: '签到成功！',
                                })
                            }
                        })
                        const sql3 = `insert into sign_record set ?`
                        db.query(sql3, {
                            open_id: openid,
                            get_jf: Number(a[(Number(results[0].days) + 1)].sign_num),
                            qd_time: new Date(),
                        }, (err, results) => {
                        })
                    })
                } else {
                    res.send({
                        status: 200,
                        message: '今日已签到',
                    })
                }
            }
            if (results.length == 0) {
                const sql = `select value from sign_config`
                db.query(sql, (err, results2) => {
                    let a = []
                    results2.map(res => {
                        a.push(JSON.parse(res.value))
                    })
                    const sql2 = `insert into user_sign set ?`
                    db.query(sql2, {
                        open_id: openid,
                        integral: a[0].sign_num,
                        sign_time: new Date(),
                        days: 1,
                        is_sign: 1
                    }, (err, results) => {
                        res.send({
                            status: 200,
                            message: '积分签到成功！',
                        })
                    })
                    const sql3 = `insert into sign_record set ?`
                    db.query(sql3, {
                        open_id: openid,
                        get_jf: a[0].sign_num,
                        qd_time: new Date(),
                    }, (err, results) => {
                    })
                })
            }
        })
    } else {
        res.send({
            status: 200,
            message: '今日已签到',
        })
        console.log('已签到', openid, flag);
    }
}

//是否签到
async function issign(req) {
    const token = req.headers.authorization.replace("Bearer ", "");
    const secret_key = config.jwtSecretKey
    const { openid } = await util.jwt(token, secret_key)
    const flag = await util.query(openid)
    // console.log(flag, openid);
    return { flag, openid }
}
//获取open_id
async function get_openid(req) {
    const token = req.headers.authorization.replace("Bearer ", "");
    const secret_key = config.jwtSecretKey
    const { openid } = await util.jwt(token, secret_key)
    return openid
}
const util = {
    jwt(token, secret_key) {
        return new Promise((resolve, reject) => {
            jwt.verify(token, secret_key, (error, decoded) => {
                if (error) {
                    console.log(`传值有问题: ${error.message}`);
                    reject(error)
                }
                // console.log(decoded);
                resolve(decoded)
            })
        })
    },
    query(openId) {
        // console.log(openId);
        return new Promise((resolve, reject) => {
            const sql = `select * from user_sign where open_id='${openId}'`
            db.query(sql, (err, results) => {
                // console.log(results);
                if (results.length == 1 && results[0].open_id == openId) {
                    //时间是否一致 已签到false
                    // console.log((results[0].sign_time).getDate(), new Date().getDate());
                    // console.log(results[0].is_sign)
                    // console.log(results);
                    if ((results[0].sign_time).getDate() != new Date().getDate()) {
                        const sql2 = `update user_sign set ? where open_id='${openId}'`
                        db.query(sql2, {
                            is_sign: 0
                        }, (err, results2) => {
                            // if (err) return res.cc(err)
                            // if (results.affectedRows == 1) { }
                            console.log(results[0].is_sign, 'asdad')
                        })
                    }
                    if ((results[0].sign_time).getDate() == new Date().getDate() && results[0].is_sign == 0) {
                        resolve(false)
                    } else {
                        console.log('111');
                        resolve(true)

                    }

                }
                else if (results.length == 0) {
                    resolve(false)
                }
                // else {
                //     resolve(true)
                // }
            })
        })
    }
}


